//
//  HMNetworkTools.swift
//  3.Swift中网络的封装
//
//  Created by heima on 16/4/8.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import AFNetworking

//定义一个结构体
struct API{
//    线上环境
    static let onlineHost = "https://api.weibo.com/"
//    测试环境用的,在上架App之前一定要替换过来
    static let devHost = "https://dev.api.weibo.com/"
    
    static let authrizen = "oauth2/access_token"
    static let access_token = "2/users/show.json"
    //    获取当前登录用户及其所关注用户的最新微博的api
    static let homePage = "2/statuses/home_timeline.json"
//    发布一个文本微博
    static let sendStatus = "2/statuses/update.json"
//    发布带有图片的微博
    static let uploadImage = "https://upload.api.weibo.com/2/statuses/upload.json"

}
//swift 中的枚举
enum HMHttpMethods: String {
    case POST = "POST"
    case GET = "GET"
}

class HMNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: HMNetworkTools = {
//        添加baseURL
        let tools = HMNetworkTools(baseURL: NSURL(string: API.onlineHost))
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
//    根据code去加载access_token
    func loadAccessToken(code:String,finished:(result:AnyObject?,error:NSError?) -> ()){
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        request(.POST, urlString: API.authrizen, parameters: parameters, finished: finished)

    }
    
//    根据access_token获取用户信息
    func loadUserInfo(token:AnyObject , uid:AnyObject,finished:(result:AnyObject?,error:NSError?) -> ()){
        let parameters = ["access_token":token,"uid":uid]
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        "https://api.weibo.com/oauth2/access_token"
        //    查询用户信息
        request(.GET, urlString: API.access_token, parameters: parameters, finished: finished)

    }
    
//    根据access_token加载用户首页信息
    func loadHomeInfo(access_token:String,max_id:Int64,since_id:Int64,finished:(result:AnyObject?,error:NSError?) -> ()){
        var parameters = ["access_token":access_token]
//       他们两个都有可能为空,如果为空就不加载
        if max_id > 0{
            parameters["max_id"] = "\(max_id-1)"
        }
        if since_id > 0{
            parameters["since_id"] = "\(since_id)"
        }
        request(.GET, urlString: API.homePage, parameters: parameters, finished: finished)
    }
    
// 发布一条文本微博数据或发布微博带有图片
    func sendStatus(access_token:String,status:String,imageList:[UIImage],finished:(result: AnyObject?, error:NSError?) -> ()){
        let parameters = ["access_token":access_token,"status":status]
        
//        判断是否有图片
        if imageList.count>0{
//            有图片,将图片转为二进制
            POST(API.uploadImage, parameters: parameters, constructingBodyWithBlock: { (formData) in
                /**
                 *将要上传的二进制数据添加到formdata
                 *
                 *  @param data  要上传的二进制数据
                 *  @param name  服务器接收上传文件的字段名
                 *  @param fileName  服务器获取到文件之后 以什么名称存储  名字可以随便取,新浪微博会按照自己的命名规则命名
                 *  @param mimeType   文件类型
                 *
                 *  @return
                 */
                // 第一个 '!' 表示一定获取一张图片  第二个 '!' 一定要将获取的图片转换 二进制
                for (index,image) in imageList.enumerate() {
//                获取图片二进制
                   let imageData = UIImagePNGRepresentation(image)
                    formData.appendPartWithFileData(imageData!, name: "pic", fileName: "xxxx\(index)", mimeType: "image/jpeg")
                }
                }, success: { (_, result) in
                    finished(result: result, error: nil)
                }, failure: { (_, error) in
                    finished(result: nil, error: error)
            })
        }else{
//            发布文本微博
            request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
        }
        
    }
    
}
extension HMNetworkTools{
    //封装所有的网络请求方法 所有的网络请求都是通过这个方法和 AFN进行联系
    func request(method: HMHttpMethods,urlString: String, parameters: AnyObject?, finished: (result: AnyObject?, error: NSError?) -> ()) {
        
        //swift中就不能够使用利用协议 欺骗Xcode
        //为了达到封装的目的 可以将相同的闭包 抽取出来,当做参数传递给AFN框架
        let success =  { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            //执行成功的回调
            finished(result: result, error: nil)
        }
        
        //定义失败的回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            //执行失败的回调
            finished(result: nil, error: error)
        }
        
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
}